import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Button } from 'antd';
import styles from './../Users.css';
import moment from 'moment';
import Factory from '../../factory';
import dataEditCreate from '../../addons/DataEdit'
import * as datetime from '../../../utils/datetime'
import dataTableCreate from '../../addons/DataTable'
import * as otherService from '../../../services/other';
const daoName = "INDI_BXBL_WH";
const ButtonGroup = Button.Group;
const columns = [
  { title: '年月', width: 160, sorter: true, dataIndex: 'YF', key: 'YF', dispaly: true, filter: true, export: false },
  { title: '投保日期', width: 120, sorter: true, key: 'TBRQ', caption: "TBRQ", render: data => datetime.format(data.TBRQ, "yyyy-MM-dd"), dispaly: true, filter: true, export: true },
  { title: '销售支行', width: 160, sorter: true, dataIndex: 'XSZH', key: 'XSZH', dispaly: true, filter: true, export: true },
  { title: '保险公司', width: 250, sorter: true, dataIndex: 'BXGS', key: 'BXGS', dispaly: true, filter: true, export: true },
  { title: '投保单号', width: 200, sorter: true, dataIndex: "TBDH", key: 'TBDH', dispaly: true, filter: true, export: true },
  { title: '投保人姓名', width: 160, sorter: true, dataIndex: "TBRXM", key: 'TBRXM', dispaly: true, filter: true, export: true },
  { title: '投保人证件号码', width: 160, sorter: true, dataIndex: "TBRZJHM", key: 'TBRZJHM', dispaly: true, filter: true, export: true },
  { title: '险种名称', width: 250, sorter: true, dataIndex: 'XZMC', key: 'XZMC', dispaly: true, filter: true, export: true },
  { title: '险种', width: 250, sorter: true, dataIndex: "XZ", key: 'XZ', dispaly: true, filter: true, export: true },
  { title: '首期保费（元）', width: 160, sorter: true, dataIndex: 'SQBF', key: 'SQBF', dispaly: true, filter: true, export: true },
  { title: '保险合同号（保单号）', width: 200, sorter: true, dataIndex: "BXHTH", key: 'BXHTH', dispaly: true, filter: true, export: true },
  { title: '合同生效日期', width: 160, sorter: true, key: 'HTSXRQ', caption: "HTSXRQ", render: data => datetime.format(data.HTSXRQ, "yyyy-MM-dd"), dispaly: true, filter: true, export: true },
  { title: '回执签收', width: 120, sorter: true, dataIndex: 'HZQS', key: 'HZQS', dispaly: true, filter: true, export: true },
  { title: '销售人', width: 120, sorter: true, dataIndex: "XSR", key: 'XSR', dispaly: true, filter: false, export: true },
  { title: '推荐人', width: 120, sorter: true, dataIndex: "TJR", key: 'TJR', dispaly: true, filter: false, export: true },
  { title: '趸交/期交', width: 140, sorter: true, dataIndex: 'DJ_QJ', key: 'DJ_QJ', dispaly: true, filter: false, export: true },
  { title: '是否犹退', width: 140, sorter: true, dataIndex: "SFYT", key: 'SFYT', dispaly: true, filter: false, export: true },
  { title: '购买渠道', width: 140, sorter: true, dataIndex: 'GMQD', key: 'GMQD', dispaly: true, filter: true, export: true },
  { title: '财产保险/人身保险', width: 180, sorter: true, dataIndex: "CCBX_RSBX", key: 'CCBX_RSBX', dispaly: true, filter: false, export: true },
  { title: '类型', width: 120, sorter: true, dataIndex: "LX", key: 'LX', dispaly: true, filter: false, export: true },
  { title: '备注', width: 120, sorter: true, dataIndex: "BZ", key: 'BZ', dispaly: true, filter: false, export: true },
  { title: '中收比率', width: 120, sorter: true, dataIndex: "ZSBL", key: 'ZSBL', dispaly: true, filter: false, export: true },
  { title: '中收', width: 120, sorter: true, dataIndex: "ZS", key: 'ZS', dispaly: true, filter: false, export: true },
  { title: '归属机构', width: 120, sorter: true, dataIndex: "GSJG", key: 'GSJG', dispaly: true, filter: false, export: true },
  { title: '销售金额（万元）', width: 150, sorter: true, dataIndex: "XSJE", key: 'XSJE', dispaly: true, filter: false, export: true },
  { title: '中收（万元）', width: 120, sorter: true, dataIndex: "ZSJE", key: 'ZSJE', dispaly: true, filter: false, export: true },
  { title: '业绩归属人', width: 120, sorter: true, dataIndex: "YJGSR", key: 'YJGSR', dispaly: true, filter: false, export: true },
];
const controls = [
  { name: 'YF', required: true, type: 'text', label: '年月', grid: 12 / 24, placeholder: "按YYYYMM格式输入,例如:202201", min: 6, max: 6 },
  { name: 'TBRQ', label: "投保日期", dataType: "date", type: "date", grid: 12 / 24 },
  { name: 'XSZH', type: 'text', label: '销售支行', grid: 12 / 24 },
  { name: 'BXGS', type: 'text', label: '保险公司', grid: 12 / 24 },
  { name: 'TBDH', label: "投保单号", type: "text", grid: 12 / 24 },
  { name: 'TBRXM', label: "投保人姓名", type: "text", grid: 12 / 24 },
  { name: 'TBRZJHM', label: '投保人证件号码', type: "text", grid: 12 / 24 },
  { name: 'XZMC', type: 'text', label: '险种名称', grid: 12 / 24 },
  { name: 'XZ', type: 'text', label: '险种（财产/人寿/年金/意外伤害/健康）', grid: 12 / 24 },
  { name: 'SQBF', label: "首期保费（元）", type: "text", grid: 12 / 24 },
  { name: 'BXHTH', type: 'text', label: '保险合同号（保单号）', grid: 12 / 24 },
  { name: 'HTSXRQ', label: "合同生效日期", dataType: "date", type: "date", grid: 12 / 24 },
  { name: 'HZQS', label: '回执签收', type: "text", grid: 12 / 24 },
  { name: 'XSR', type: 'text', label: '销售人', grid: 12 / 24 },
  { name: 'TJR', type: 'text', label: '推荐人', grid: 12 / 24 },
  { name: 'DJ_QJ', label: "趸交/期交（*年）", type: "text", grid: 12 / 24 },
  { name: 'SFYT', label: "是否犹退（是/否）", type: "text", grid: 12 / 24 },
  { name: 'GMQD', label: "购买渠道（银保通/线下单/网银/手机银行）", type: "text", grid: 12 / 24 },
  { name: 'CCBX_RSBX', label: '财产保险/人身保险', type: "text", grid: 12 / 24 },
  { name: 'LX', label: '类型（人寿/年金/意外伤害/健康）', type: "text", grid: 12 / 24 },
  { name: 'BZ', type: 'text', label: '备注', grid: 12 / 24 },
  { name: 'ZSBL', type: 'text', label: '中收比率', grid: 12 / 24 },
  { name: 'ZS', type: 'text', label: '中收', grid: 12 / 24 },
  { name: 'GSJG', type: 'text', label: '归属机构', grid: 12 / 24 },
  { name: 'XSJE', type: 'text', label: '销售金额（万元）', grid: 12 / 24 },
  { name: 'ZSJE', type: 'text', label: '中收（万元）', grid: 12 / 24 },
  { name: 'YJGSR', type: 'text', label: '业绩归属人', grid: 12 / 24 },
  { name: 'DRJG', required: false, ignore: true, type: 'text', label: '导入结果', grid: 12 / 24 },
]
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class BxtzWhForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataChange: false,
      ny: moment().subtract(1, 'month'),
      searchData: {},
      dataList: []
    };
  }
  componentDidMount() {
    this.props.dispatch({
      type: `${daoName}/setKeyName`,
      payload: { keyName: "ID", permID: this.props.permID }
    });
    this.loadData();
  }
  loadData() {
    let ny = this.state.ny.format("YYYYMM")
    let { permID, popedomTypes, userID, orgID, pOrgID } = this.props
    const pTypes = popedomTypes[permID]
    let whereItems = [];
    let WhereCauses = [];
    if (pTypes.indexOf('4') !== -1) {
      whereItems.push({
        FieldName: "YF",
        Operator: "=",
        FieldValues: ny
      })
    } else if (pTypes.indexOf('4') === -1 && pTypes.indexOf('2') !== -1) {
      whereItems.push({
        FieldName: "YF",
        Operator: "=",
        FieldValues: ny
      }, {
        FieldName: "UTID",
        Operator: "=",
        FieldValues: '' + pOrgID
      })
    }
    WhereCauses.push({
      WhereItems: whereItems,
      RelationSign: "AND"
    })
    let seeks = WhereCauses
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, page: 1, pageSize: 20, seeks }
    });
  }
  loadOptionData() {
    let options = []
    controls.map(c => {
      if (c.fetch) {
        let f = c.fetch;
        if (c.type === 'cascader-select') {
          f.isCascader = true;
        }
        if (c.type !== 'search') {
          options.push(f);
        }
      }
    })
    if (daoName && options.length > 0) {
      this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
    }
  }
  findList() {
    let ny = ""
    const form = this.refs.EditForm.getForm();
    form.validateFields((err, values) => {
      let d = new Date(values.NY)
      ny = datetime.format(d, 'yyyyMM')
    });
    let { permID, popedomTypes, userID, orgID, pOrgID } = this.props
    const pTypes = popedomTypes[permID]
    let whereItems = [];
    let WhereCauses = [];
    if (pTypes.indexOf('4') !== -1) {
      whereItems.push({
        FieldName: "YF",
        Operator: "=",
        FieldValues: ny
      })
    } else if (pTypes.indexOf('4') === -1 && pTypes.indexOf('2') !== -1) {
      whereItems.push({
        FieldName: "YF",
        Operator: "=",
        FieldValues: ny
      }, {
        FieldName: "UTID",
        Operator: "=",
        FieldValues: '' + orgID
      })
    }
    WhereCauses.push({
      WhereItems: whereItems,
      RelationSign: "AND"
    })
    let seeks = WhereCauses
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, page: 1, pageSize: 20, seeks }
    });
  }
  searchHandle(data) {
    this.state.searchData = data
  };
  tzsd() {
    let ny = ""
    const form = this.refs.EditForm.getForm();
    form.validateFields((err, values) => {
      let d = new Date(values.NY)
      ny = datetime.format(d, 'yyyyMM')
    });
    let n = ny.toString().substring(0, 4)
    let y = ny.toString().substring(4, 6)
    Modal.confirm({
      title: '提示',
      content: `你确认锁定【` + n + `年` + y + `月】的客户经理调整吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        otherService.JjTzsd2({ ny }
        ).then(function (data) {
          if (data === 'OK') {
            message.success('锁定成功！')
          } else {
            message.error('锁定失败！' + data)
            return;
          }
        }.bind(this)).catch(function (ex) {
          console.log('请求出错', ex)
        });
      }
    });
  }
  onSelectChangeHandler(newList) {
    this.setState({ dataList: newList })
  }
  Bxtztz() {
    const len = this.props.selectedRowKeys.length;
    if (len === 0) {
      message.error('请选择要调整的数据行！');
      return;
    }
    let isOK = true;
    let zjhm = ''
    let key = this.props.selectedRowKeys[0]
    const form = this.refs.EditForm.getForm();
    form.validateFields((err, values) => {
      if (!err) {
        if (values.ZJHM === undefined || values.ZJHM === '') {
          message.error('证件号码不能为空！');
          isOK = false;
        } else {
          zjhm = values.ZJHM
        }
      }
    });
    if (!isOK) {
      return;
    }
    otherService.Bxtztz({ key,zjhm }
    ).then(function (data) {
      if (data === 'OK') {
        message.success('设置成功！')
        this.componentDidMount()
      } else {
        message.error('设置失败，证件号码在系统中不存在！')
        return;
      }
    }.bind(this)).catch(function (ex) {
      console.log('请求出错', ex)
    });
    // if (this.state.dataList[0].ISSD === 1) {
    //   message.error('该月的数据调整已结束，不能进行调整了。');
    //   return
    // }
    // let key = this.props.selectedRowKeys[0]
    // let emid = this.state.searchData.ID
    // Modal.confirm({
    //   title: '提示',
    //   content: `你确认要设置证据号码为【` + zjhm + `】吗？`,
    //   okText: '确定',
    //   cancelText: '取消',
    //   onOk: () => {
    //     otherService.Bxtztz({ key, emid }
    //     ).then(function (data) {
    //       if (data === 'OK') {
    //         message.success('调整成功！')
    //         this.componentDidMount()
    //       } else {
    //         message.error('调整失败！' + data)
    //         return;
    //       }
    //     }.bind(this)).catch(function (ex) {
    //       console.log('请求出错', ex)
    //     });
    //   }
    // });
  }
  tzjs() {
    let ny = ""
    const form = this.refs.EditForm.getForm();
    form.validateFields((err, values) => {
      let d = new Date(values.NY)
      ny = datetime.format(d, 'yyyyMM')
    });
    let n = ny.toString().substring(0, 4)
    let y = ny.toString().substring(4, 6)
    Modal.confirm({
      title: '提示',
      content: `你确认解除【` + n + `年` + y + `月】的客户经理调整锁定吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        otherService.JjTzjs2({ ny }
        ).then(function (data) {
          if (data === 'OK') {
            message.success('锁定成功！')
          } else {
            message.error('锁定失败！' + data)
            return;
          }
        }.bind(this)).catch(function (ex) {
          console.log('请求出错', ex)
        });
      }
    });
  }
  render() {
    let { record, permID, popedomTypes } = this.props
    const pTypes = popedomTypes[permID]
    let controlsFilter = []
    controlsFilter =
      [
        { name: 'NY', required: true, type: 'month', label: '日期', grid: 4 / 24, dataType: 'month', layout: { labelSpan: 8, wrapperSpan: 15 } },
        {
          name: 'BT', required: false, type: 'button-group',
          data: [
            { value: '1', label: '查询', onClick: this.findList.bind(this) },
          ], grid: 2 / 24
        },
      ];
    if (pTypes.indexOf('4') !== -1) {
      controlsFilter = [
        { name: 'NY', required: true, type: 'month', label: '日期', grid: 4 / 24, dataType: 'month', layout: { labelSpan: 8, wrapperSpan: 15 } },
        {
          name: 'BT', required: false, type: 'button-group',
          data: [
            { value: '1', label: '查询', onClick: this.findList.bind(this) },
            // { value: '2', label: '锁定', onClick: this.tzsd.bind(this) },
            // { value: '3', label: '解锁', onClick: this.tzjs.bind(this) },

          ], grid: 4 / 24
        },
      ];
    }
    if (pTypes.indexOf('2') !== -1) {
      controlsFilter = [
        { name: 'NY', required: true, type: 'month', label: '日期', grid: 4 / 24, dataType: 'month', layout: { labelSpan: 8, wrapperSpan: 15 } },
        {
          name: 'BT', required: false, type: 'button-group',
          data: [
            { value: '1', label: '查询', onClick: this.findList.bind(this) },
          ], grid: 2 / 24
        },
        { name: 'ZJHM', required: false, type: 'text', label: '证件号码', grid: 8 / 24 },
        {
          name: 'BT', required: false, type: 'button-group',
          data: [
            { value: '1', label: '设置', onClick: this.Bxtztz.bind(this) },
          ], grid: 2 / 24
        },
      ];
    }
    if (pTypes.indexOf('2') !== -1 && pTypes.indexOf('4') !== -1) {
      controlsFilter = [
        { name: 'NY', required: true, type: 'month', label: '日期', grid: 4 / 24, dataType: 'month', layout: { labelSpan: 8, wrapperSpan: 15 } },
        {
          name: 'BT', required: false, type: 'button-group',
          data: [
            { value: '1', label: '查询', onClick: this.findList.bind(this) },
          ], grid: 2 / 24
        },
        { name: 'ZJHM', required: false, type: 'text', label: '证件号码', grid: 8 / 24 },
        {
          name: 'BT', required: false, type: 'button-group',
          data: [
            { value: '1', label: '设置', onClick: this.Bxtztz.bind(this) },
            // { value: '2', label: '锁定', onClick: this.tzsd.bind(this) },
            // { value: '3', label: '解锁', onClick: this.tzjs.bind(this) },

          ], grid: 4 / 24
        },
      ];
    }
    let ny = this.state.ny.format("YYYYMM")
    const seekRecord = { NY: ny }
    return (
      <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
        <div>
          <div className={styles.create}>
            <EditFrom ref="EditForm" daoName={daoName} controls={controlsFilter} record={seekRecord} clearItemMargin={true} />
          </div>
          <DataTable ref="paraTable" daoName={daoName} columns={columns} controls={controls} permID={permID} onSelectChange={this.onSelectChangeHandler.bind(this)} />
        </div>
      </div>
    )
  }
}
function mapStateToProps(state) {
  const { showEdit, record, selectedRowKeys, keyName } = state[daoName];
  const { userID, orgID, pOrgID, popedomTypes, odsDate } = state.menus;
  return {
    userID,
    orgID,
    pOrgID,
    popedomTypes,
    showEdit,
    selectedRowKeys,
    keyName,
    record, odsDate,
  }
}
BxtzWhForm = connect(mapStateToProps)(BxtzWhForm)
export default BxtzWhForm;

let render = (props) => React.createElement(BxtzWhForm, props);
let f = new Factory()
f.set("BxtzWhForm", render)
